import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';

/// 缩放拖拽组件
/// 提供Ctrl+滚轮缩放、Ctrl+左键拖拽功能
class ZoomDragWidget extends StatefulWidget {
  /// 子组件
  final Widget child;
  
  /// 最小缩放比例
  final double minScale;
  
  /// 最大缩放比例
  final double maxScale;
  
  /// 缩放步长
  final double scaleStep;
  
  /// 是否启用缩放功能
  final bool enableZoom;
  
  /// 是否启用拖拽功能
  final bool enableDrag;
  
  /// 缩放变化回调
  final ValueChanged<double>? onScaleChanged;
  
  /// 拖拽变化回调
  final ValueChanged<Offset>? onDragChanged;
  
  /// 重置回调
  final VoidCallback? onReset;

  const ZoomDragWidget({
    Key? key,
    required this.child,
    this.minScale = 0.5,
    this.maxScale = 3.0,
    this.scaleStep = 0.1,
    this.enableZoom = true,
    this.enableDrag = true,
    this.onScaleChanged,
    this.onDragChanged,
    this.onReset,
  }) : super(key: key);

  @override
  State<ZoomDragWidget> createState() => ZoomDragWidgetState();
}

class ZoomDragWidgetState extends State<ZoomDragWidget> {
  double _currentScale = 1.0;
  Offset _currentOffset = Offset.zero;
  bool _isCtrlPressed = false;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _focusNode.requestFocus();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  /// 重置缩放和拖拽
  void resetZoom() {
    setState(() {
      _currentScale = 1.0;
      _currentOffset = Offset.zero;
    });
    widget.onScaleChanged?.call(_currentScale);
    widget.onDragChanged?.call(_currentOffset);
    widget.onReset?.call();
  }

  /// 设置缩放比例
  void setScale(double scale) {
    final newScale = scale.clamp(widget.minScale, widget.maxScale);
    setState(() {
      _currentScale = newScale;
    });
    widget.onScaleChanged?.call(_currentScale);
  }

  /// 设置拖拽偏移
  void setTranslate(double x, double y) {
    setState(() {
      _currentOffset = Offset(x, y);
    });
    widget.onDragChanged?.call(_currentOffset);
  }

  /// 获取当前缩放比例
  double getCurrentScale() {
    return _currentScale;
  }

  /// 获取当前拖拽偏移
  Offset getCurrentTranslate() {
    return _currentOffset;
  }

  /// 处理滚轮缩放
  void _handlePointerSignal(PointerSignalEvent event) {
    if (event is PointerScrollEvent && _isCtrlPressed) {
      final delta = event.scrollDelta.dy > 0 ? -widget.scaleStep : widget.scaleStep;
      final newScale = (_currentScale + delta).clamp(widget.minScale, widget.maxScale);
      
      if (newScale != _currentScale) {
        setScale(newScale);
      }
    }
  }

  /// 处理拖拽
  void _handlePanUpdate(DragUpdateDetails details) {
    if (_isCtrlPressed) {
      setState(() {
        _currentOffset += details.delta;
      });
      widget.onDragChanged?.call(_currentOffset);
    }
  }

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: _focusNode,
      onKey: (RawKeyEvent event) {
        // 处理Ctrl按键状态
        if (event is RawKeyDownEvent) {
          if (event.isControlPressed) {
            _isCtrlPressed = true;
            // 处理Ctrl+0重置快捷键
            if (event.logicalKey == LogicalKeyboardKey.digit0) {
              resetZoom();
            }
          }
        } else if (event is RawKeyUpEvent) {
          if (!event.isControlPressed) {
            _isCtrlPressed = false;
          }
        }
      },
      child: Listener(
        onPointerSignal: _handlePointerSignal,
        child: GestureDetector(
          onPanUpdate: _handlePanUpdate,
          child: Transform(
            transform: Matrix4.identity()
              ..translate(_currentOffset.dx, _currentOffset.dy)
              ..scale(_currentScale),
            alignment: Alignment.center,
            child: SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: Stack(
                children: [
                  // 主要内容
                  widget.child,
                  
                  // 状态显示（可选）
                  if (_currentScale != 1.0 || _currentOffset != Offset.zero)
                    Positioned(
                      top: 16,
                      right: 16,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.black54,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          'Scale: ${_currentScale.toStringAsFixed(1)}x\n'
                          'Offset: (${_currentOffset.dx.toStringAsFixed(0)}, '
                          '${_currentOffset.dy.toStringAsFixed(0)})',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// 缩放拖拽控制器扩展
extension ZoomDragControllerExtension on ZoomDragWidgetState {
  /// 启用缩放功能
  void enableZoom() {
    // 缩放功能通过widget.enableZoom控制，这里可以添加运行时控制逻辑
    debugPrint('Zoom enabled');
  }

  /// 禁用缩放功能
  void disableZoom() {
    // 缩放功能通过widget.enableZoom控制，这里可以添加运行时控制逻辑
    debugPrint('Zoom disabled');
  }

  /// 启用拖拽功能
  void enableDrag() {
    // 拖拽功能通过widget.enableDrag控制，这里可以添加运行时控制逻辑
    debugPrint('Drag enabled');
  }

  /// 禁用拖拽功能
  void disableDrag() {
    // 拖拽功能通过widget.enableDrag控制，这里可以添加运行时控制逻辑
    debugPrint('Drag disabled');
  }
}